package com.huarui.user.action;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang.xwork.StringUtils;

/**
 * 解决JBoss与Apache协作下的 remote ip 问题
 * 
 * @author jacky.chenb
 */
public class RemoteIpRequestWrapper extends HttpServletRequestWrapper {

	private static final String HOST = "Host";
	private static final String X_FORWARDED_HOST = "x-forwarded-host";
	
	private static final String ORIG_CLIENT_IP = "ORIG_CLIENT_IP";
	private static final String X_FORWARDED_FOR = "x-forwarded-for";

	
	public RemoteIpRequestWrapper(HttpServletRequest request) {
		super(request);
	}
	
	public String getRemoteAddr() {
		String ip = ((HttpServletRequest) getRequest()).getHeader(ORIG_CLIENT_IP);

		if (ip == null) {
			ip = getXHeader(X_FORWARDED_FOR);
		}

		if (ip == null) {
			ip = super.getRemoteAddr();
		}

		return ip;
	}
	
	public String getHeader(String name) {
		String httpHeader = null;

		if (HOST.equalsIgnoreCase(name)) {
			httpHeader = getXHeader(X_FORWARDED_HOST);
		}

		if (httpHeader == null) {
			httpHeader = super.getHeader(name);
		}

		return httpHeader;
	}

	public StringBuffer getRequestURL() {
		StringBuffer url = super.getRequestURL();
		
		String host = super.getHeader(HOST);
		String realhost = this.getHeader(HOST);
		
		if (realhost != null && !realhost.equals(host)) {
			int start = url.indexOf("://") + 3;
			return url.replace(start, start + host.length(), realhost);
		} else {
			return url;
		}
	}

	@SuppressWarnings("unchecked")
	private String getXHeader(String name) {
		Enumeration e = ((HttpServletRequest) getRequest()).getHeaders(name);
		if (e != null && e.hasMoreElements()) {
			String headers = (String) e.nextElement();
			if (!StringUtils.isBlank(headers)) {
				return headers.split("\\s*,\\s*")[0];
			}
		}

		return null;
	}


}